<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getequipmentlist } from '@/api/echarts';

export default {
  name: "map-view",
  data() {
    return {
      map: null,
      points: [],
      markers: [],
      cluster: null,
      geocoder: null, // 逆地理编码器
      district: {
        // 定义行政区域中心点，示例数据
        Beijing: { center: '116.405285,39.904989' },
        Shanghai: { center: '121.473701,31.230416' },
        Wuhan: { center: '114.305393,30.593099' },
        Guangzhou: { center: '113.264385,23.129112' },
        Chaoyang: { center: '116.450000,39.920000' },
        Haidian: { center: '116.310000,39.950000' },
        Pudong: { center: '121.550000,31.220000' },
        Jingan: { center: '121.460000,31.230000' },
        Jianghan: { center: '114.270000,30.580000' },
        Wuchang: { center: '114.340000,30.540000' },
        Tianhe: { center: '113.330000,23.140000' },
        Yuexiu: { center: '113.270000,23.130000' },
        Wangjing: { center: '116.470000,39.990000' },
        Zhongguancun: { center: '116.310000,39.980000' },
        Shangdi: { center: '116.320000,40.020000' },
        Lujiazui: { center: '121.550000,31.240000' },
        NanjingRoad: { center: '121.480000,31.230000' },
        Xintiandi: { center: '121.480000,31.220000' },
        Hankou: { center: '114.270000,30.600000' },
        Guanggu: { center: '114.400000,30.510000' },
        ZhujiangNewTown: { center: '113.330000,23.140000' },
        BeijingRoad: { center: '113.270000,23.130000' },
      },
      clusterIndexSet: {
        city: { minZoom: 2, maxZoom: 10 },
        district: { minZoom: 10, maxZoom: 12 },
        area: { minZoom: 12, maxZoom: 15 },
        community: { minZoom: 15, maxZoom: 22 },
      },
    };
  },
  created() {
    this.fetchEquipmentList();
  },
  mounted() {
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    async fetchEquipmentList() {
    try {
      const res = await getequipmentlist({ limit: 10000000 });
      console.log(res, "研究地图");

      // 提取所有对象的 lat 和 lng 属性并过滤掉没有经纬度的数据
      this.points = res.msg
        .filter(item => item.lat && item.lng)
        .map(item => ({
          lnglat: [parseFloat(item.lng), parseFloat(item.lat)],
          city: item.city || '鞍山',
          district: item.district || 'Unknown',
          street: item.street || 'Unknown',
        }));

      console.log('Filtered points:', this.points); // 打印提取的 points 数组

      // 初始化标记
      this.initMarkers();

      // 初始化聚合器
      if (this.map) {
        this.initCluster();
      }

      // 获取行政区域信息
      await this.getAddressesFromPoints(this.points);
    } catch (error) {
      console.error('Error fetching equipment list:', error);
    }
  },
  async getAddressesFromPoints(points) {
    if (!this.geocoder) {
      console.error('Geocoder is not initialized.');
      return;
    }

    for (const point of points) {
      try {
        const address = await this.getAddressFromCoordinates(point.lnglat[0], point.lnglat[1]);
        console.log(`坐标 (${point.lnglat[0]}, ${point.lnglat[1]}) 对应的地址是: ${address}`);
      } catch (error) {
        console.error(`获取坐标 (${point.lnglat[0]}, ${point.lnglat[1]}) 的地址失败: ${error}`);
      }
    }
  },
  async getAddressFromCoordinates(lng, lat) {
    return new Promise((resolve, reject) => {
      if (!this.geocoder) {
        reject(new Error('Geocoder is not initialized.'));
        return;
      }

      this.geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const address = result.regeocode.formattedAddress || '未知地址';
          resolve(address);
        } else {
          reject(new Error('地理编码失败'));
        }
      });
    });
  },
    renderClusterMarker(context) {
      const styleObj = this.getStyle(context);
      const div = document.createElement("div");
      div.className = "amap-cluster";
      div.style.backgroundColor = styleObj.bgColor;
      div.style.width = `${styleObj.size}px`;
      div.style.height = `${styleObj.size}px`;

      if (styleObj.index <= 2) {
        div.style.height = `${styleObj.size}px`;
        context.marker.on("click", (e) => {
          let curZoom = this.map.getZoom();
          if (curZoom < 20) {
            curZoom += 1;
          }
          this.map.setZoomAndCenter(curZoom, e.lnglat);
        });
      }

      div.style.border = `solid 1px ${styleObj.borderColor}`;
      div.style.borderRadius = `${styleObj.size / 2}px`;
      div.innerHTML = styleObj.text;
      div.style.color = styleObj.color;
      div.style.textAlign = styleObj.textAlign;
      div.style.boxShadow = styleObj.boxShadow;
      context.marker.setContent(div);

      const position = this.getPosition(context);
      if (position) {
        context.marker.setPosition(position);
      }
      context.marker.setAnchor("center");
    },
    getStyle(context) {
      const { clusterData, index, count } = context;
      const color = ["8,60,156", "66,130,198", "107,174,214", "78,200,211"];
      const indexs = ["city", "district", "area", "community"];
      const i = indexs.indexOf(index.mainKey);
      let text = clusterData[0][index.mainKey];
      let size = Math.round(30 + Math.pow(count / this.points.length, 1 / 5) * 70);

      if (i <= 2) {
        const extra = `<span class="showCount">${context.count}个</span>`;
        text = `<span class="showName">${text}</span>` + extra;
      } else {
        size = 12 * text.length + 20;
      }

      return {
        bgColor: `rgba(${color[i]},.8)`,
        borderColor: `rgba(${color[i]},1)`,
        text,
        size,
        index: i,
        color: "#ffffff",
        textAlign: "center",
        boxShadow: "0px 0px 5px rgba(0,0,0,0.8)",
      };
    },
    getPosition(context) {
      const key = context.index.mainKey;
      const dataItem = context.clusterData && context.clusterData[0];
      const districtName = dataItem[key];
      if (!this.district[districtName]) {
        return null;
      }
      const center = this.district[districtName].center.split(",");
      return new AMap.LngLat(center[0], center[1]);
    },
    getClusterStyles() {
      const color = ["8,60,156", "66,130,198", "107,174,214", "78,200,211"];
      return color.map((c) => ({
        url: `data:image/svg+xml;base64,${btoa(`
          <svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
            <circle cx="32" cy="32" r="32" fill="rgba(${c},.8)" />
          </svg>
        `)}`,
        size: new AMap.Size(64, 64),
        offset: new AMap.Pixel(-32, -32),
        textColor: '#ffffff',
        textSize: 16,
      }));
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100vh; /* 使地图容器占满整个视口 */
}
.amap-cluster {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}
.showName {
  font-size: 14px;
}
.showCount,
.showName {
  display: block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
}
</style>
